package jumavidesktop.Otros.DetectMotion;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.io.File;
import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.Codec;
import javax.media.ConfigureCompleteEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.DataSink;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.PrefetchCompleteEvent;
import javax.media.Processor;
import javax.media.RealizeCompleteEvent;
import javax.media.ResourceUnavailableEvent;
import javax.media.UnsupportedPlugInException;
import javax.media.control.TrackControl;
import javax.media.format.VideoFormat;
import javax.swing.JPanel;
import jumavidesktop.Persistencia.entidades.Configdetectionmotion;
import jumavidesktop.Persistencia.entidades.EnumeracionesEntidades.TipoRecursoMotion;

/**
 *
 * @author vimso
 */
public class PuenteCamara extends JPanel implements ControllerListener{

    Processor p;
    DataSink fileW = null;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;
    Configdetectionmotion configuracion;
    LinkedList<Image> vector;

    public PuenteCamara(Configdetectionmotion configuracion, LinkedList<Image> cola) {
        this.configuracion = configuracion;
        this.vector=cola;
    }
    
    public void repintar(){
        this.updateUI();
        this.repaint();
    }

    private MediaLocator dameMediaLocator(Configdetectionmotion configuracion) {
        if(configuracion.getTipoRecurso().equals(TipoRecursoMotion.VIDEO))
        {
            try {
                File fichero= new File(configuracion.getDatosRecursos());
                 return  new MediaLocator(fichero.toURI().toURL());
            } catch (MalformedURLException ex) {
                Logger.getLogger(PuenteCamara.class.getName()).log(Level.SEVERE, null, ex);
            }
             
        }else if(configuracion.getTipoRecurso().equals(TipoRecursoMotion.URL))
        {
            return new MediaLocator(configuracion.getDatosRecursos());
        }
        return null;
    }

    /**
     * Block until the processor has transitioned to the given state. Return
     * false if the transition failed.
     */
    boolean waitForState(int state) {
        synchronized (waitSync) {
            try {
                while (p.getState() != state && stateTransitionOK) {
                    waitSync.wait();
                }
            } catch (Exception e) {}
        }
        return stateTransitionOK;
    }

    public boolean arrancaCamara() {

        try {
            p = Manager.createProcessor(this.dameMediaLocator(configuracion));            
        } catch (Exception e) {
            //Fallaría al coger el datasource

            return false;
        }

        p.addControllerListener(this);

        // Put the Processor into configured state.
        p.configure();
        if (!waitForState(p.Configured)) {
            //Fallaría al cargar la configuración
            return false;
        }

        p.setContentDescriptor(null);

        TrackControl tc[] = p.getTrackControls();

        if (tc == null) {
            //Fallo al obetner los controles del procesador 
            return false;
        }

        TrackControl videoTrack = null;

        for (int i = 0; i < tc.length; i++) {
            if (tc[i].getFormat() instanceof VideoFormat) {
                videoTrack = tc[i];
                break;
            }
        }

        if (videoTrack == null) {
            //System.err.println("The input media does not contain a video track.");            
            return false;
        }

        try {
            Codec codec[] = {new Efectos(this.configuracion, vector)};
            //Codec codec[] = {new MotionDetectionEffect()};
            videoTrack.setCodecChain(codec);
        } catch (UnsupportedPlugInException e) {
//	    System.err.println("The processor does not support effects.");
        }

        // Realize the processor.

        p.prefetch();
        
        if (!waitForState(p.Prefetched)) {
//	    System.err.println("Failed to realize the processor.");
            return false;
        }
        
        setLayout(new BorderLayout());

	Component cc;

	Component vc;
	if ((vc = p.getVisualComponent()) != null) {
	    add("Center", vc);
	}

	if ((cc = p.getControlPanelComponent()) != null) {
	    add("South", cc);
	}

	// Start the processor.
	p.start();

	setVisible(true);
        
        
        // Start the processor.
        p.start();
        return true;

    }

 
    /**
     * Controller Listener.
     */
    public void controllerUpdate(ControllerEvent evt) {


	if (evt instanceof ConfigureCompleteEvent ||
	    evt instanceof RealizeCompleteEvent ||
	    evt instanceof PrefetchCompleteEvent) {
	    synchronized (waitSync) {
		stateTransitionOK = true;
		waitSync.notifyAll();
	    }
	} else if (evt instanceof ResourceUnavailableEvent) {
	    synchronized (waitSync) {
		stateTransitionOK = false;
		waitSync.notifyAll();
	    }
	} else if (evt instanceof EndOfMediaEvent) {
	    p.close();
	    //System.exit(0);
	}
    }

}
